package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Role;
import encaps.entities.UserLocalHome;
import encaps.resources.Image;
import encaps.resources.Labels;
import encaps.resources.Response;
import encaps.utils.EntityUtil;
import encaps.utils.StringUtil;
import encaps.utils.XMLHelper;
import org.jdom.Element;

public class DeleteProfileAction extends Action {

    public static final String DELETE_PROFILE = "deleteProfile";
    public static final String SURE = "sure";
    public static final String YES = "yes";
    public static final String NO = "no";
    private ActionContext actionContext;

    public DeleteProfileAction(ActionContext context, Grant requiredGrant) {
        actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            Element result = null;
            String sure = actionContext.getTextParameter(SURE);
            if (StringUtil.isEmpty(sure)) {
                result = XMLHelper.createElement(Response.RESPONSE);
                Element e = XMLHelper.addChild(result, Response.ENTITY);
                e.setAttribute(Response.EDIT, "false");
                XMLHelper.addChild(e, XMLHelper.createHeader(Labels.getLabel(Labels.ARE_YOU_SURE_MESSAGE)));
                XMLHelper.addChild(e, XMLHelper.createImageButton(Image.getImage(Image.YES), YES, SURE));
                XMLHelper.addChild(e, XMLHelper.createImageButton(Image.getImage(Image.NO), NO, SURE));
                XMLHelper.addChild(e, XMLHelper.createHiddenTextField(DELETE_PROFILE, ACTION));
            } else if (sure.equals(YES)) {
                String role = actionContext.getUserRole();
                if (role.equals(Role.ADMIN)) {
                    return XMLHelper.createTextMessage(Labels.getLabel(Labels.ADMIN_CANNOT_BE_DELETED_MESSAGE));
                }
                result = XMLHelper.createTextMessage(Labels.getLabel(Labels.YOUR_PROFILE_DELETED_MESSAGE));
                String login = actionContext.getUserLogin();
                UserLocalHome userHome = EntityUtil.getUserHome();
                userHome.findByLogin(login).remove();
                actionContext.setUserLogin(null);
                actionContext.setUserRole(Role.GUEST);
            } else {
                result = XMLHelper.createTextMessage(Labels.getLabel(Labels.RIGHT_DECISION));
            }
            return result;
        } catch (Exception ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }
}
